from scapy.all import *

import sys
from time import time


def ping(ipAddress):
	ip = (IP(dst=ipAddress)/ICMP())
	print "sending ping over ICMP to" , ip.dst
	start = time()
	response  = sr1(ip, verbose=0)
	end = time()
	print "reciving from" , ip.dst , msTime(start,end)
#	printResponse(response)	
		
def printResponse(response):
	response.show()
		
def traceroute(destination):
    i = 1
    maxTTL = 50
    isReached = False
    responses = []
    ipPacket = (IP(dst=destination,ttl=1)/ICMP())
    while not isReached and i <= maxTTL:
        ipPacket.ttl = i
        res = sendPacket(ipPacket)
        if res[0] is None:
            resAsString = str(i) + " *"
        else:
        	if isDestReached(res[0]):
        		isReached = True
        		resAsString = cutePrint(i,res) + " ---> Destination Reached."
        	else:
        		resAsString = cutePrint(i,res)
        responses.append(resAsString)        
        i = i+1
        
    printResponses(responses)
    
def cutePrint(packetNumber,resPacket):
	 return str(packetNumber) + " " + resPacket[0][0].src + "  " + resPacket[1] 
 
def sendPacket(packet):
	start = time()
	res = sr1(packet,timeout=2, verbose = 0)
	stop = time()
	return res,msTime(start,stop)
	
def msTime(start,stop):
	return str((stop - start)*1000) + " ms"
	
def printResponses(responses):
	for p in responses:
		print p	 
		
def isDestReached(IpResponse):	
   #es un mje de tipo, echo-reply? Si lo es me respondio el destino
	return IpResponse[0][1].type == 0 

	